<?php

namespace App\Http\Controllers\Api\Doctor;

use App\Http\Controllers\ApiController;
use App\Models\MedicalRecord;
use App\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class DoctorController extends ApiController
{
    /**
     * @var \Illuminate\Http\Request
     */
    protected $request;

    /**
     * DoctorController constructor.
     * @param \Illuminate\Http\Request $request
     */
    public function __construct(Request $request)
    {
        parent::__construct();

        $this->request = $request;
    }

    public function bind()
    {
        $this->bindDoctorValidator();

        $input = $this->request->input();

        $doctor = User::select(['id', 'hospital_id'])->findOrFail($input['doctor_id']);

        $record = MedicalRecord::withoutGlobalScope('hasBindDoctor')
            ->select('id', 'hospital_id', 'visit_type')
            ->findOrFail($input['record_id']);

        if ($record->hospital_id) {
            if ($record->hospital_id != $doctor->hospital->id) {
                return $this->setMessage('医生非本医院医生')->setCode(40010)->hasNoData();
            }
        }

        $user = \Auth::user();

        $record_first = MedicalRecord::select('id', 'hospital_id', 'visit_type')
            ->where('hospital_id', $doctor->hospital->id)
            ->where('visit_type', 1)
            ->where('patient_id', $user->id)
            ->first();


        if ($record->visit_type['value'] == '复诊') {
            if (!$record_first) {
                return $this->setMessage('患者无此医院首诊信息')->setCode(40010)->hasNoData();
            }

        }

        if ($record->visit_type['value'] == '首诊') {
            if ($record_first) {
                if ($record_first->id != $input['record_id']) {
                    return $this->setMessage('患者此医院已有首诊信息')->setCode(40010)->hasNoData();
                }
            }
        }

        $record = MedicalRecord::withoutGlobalScope('hasBindDoctor')
            ->where('id', $input['record_id'])
            ->update([
                'doctor_id' => $doctor->id,
                'hospital_id' => $doctor->hospital->id,
                'clinic_at' => Carbon::now()->toDateString(),
                'is_western' => $doctor->hospital->type == 1 ? 1 : 0,
            ]);

        if ($record) {
            return $this->setMessage('绑定成功。')->setCode(10000)->hasNoData();
        } else {
            return $this->setMessage('绑定失败，未找到该病历。')->setCode(40400)->hasNoData();
        }
    }

    /**
     *  医生病历绑定 数据验证
     */
    protected function bindDoctorValidator()
    {
        $this->validate($this->request, [
            'doctor_id' => 'required|integer',
            'record_id' => 'required|integer',
        ]);
    }


}
